package com.ss.android.caijing.stepcounterlib.log;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.ss.android.caijing.stepcounterlib.utils.Util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;

/**
 * Created by zdh on 2017/11/13.
 */
public class AccelerateLog {
    String TAG = "AccelerateLog";
    private String LOG_NAME = "/acceleratelog.txt";
    private String DIR_LOG = "/logs";
    private String encoding = "GBK"; // 字符编码(可解决中文乱码问题 )
    private String mLogPath = "";

    private volatile static AccelerateLog logWriter = null;

    public static AccelerateLog instance() {
        if (logWriter == null) {
            synchronized (AccelerateLog.class) {
                if (logWriter == null) {
                    logWriter = new AccelerateLog();
                }
            }
        }
        return logWriter;
    }

    private AccelerateLog() {

    }

    public boolean initLogFile(Context context) {
        mLogPath = getLogPath(context) + LOG_NAME;
        try {
            File logFile = new File(mLogPath);
            if (logFile.exists() && logFile.isFile()) {
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(logFile), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String firstLine = bufferedReader.readLine();
                read.close();
                if (firstLine.equals(String.valueOf(Util.getTodayTime()))) {
                    return true;
                } else {
                    logFile.delete();
                    boolean isSuccess = logFile.createNewFile();
                    writeLog(Util.getTodayTime());
                    return isSuccess;
                }
            } else {
                boolean isSuccess = logFile.createNewFile();
                writeLog(Util.getTodayTime());
                return isSuccess;
            }
        } catch (Exception ex) {
            SSLog.e(TAG, ex.toString());
        }
        return false;
    }

    public synchronized void writeLog(float x, float y, float z) {
        writeLog(x + "," + y + "," + z);
    }

    synchronized void writeLog(Object value) {
        try {
            File logFile = new File(mLogPath);
            if (!logFile.exists()) return;
            if (Util.getFileSize(logFile) > 1024 * 1024 * 10) {
                logFile.delete();
                logFile.createNewFile();
                if (!logFile.exists()){
                    return;
                }
            }
            Writer writer = new OutputStreamWriter(new FileOutputStream(logFile, true), encoding);
            writer.append(value.toString()).append("\n");
            writer.flush();
            writer.close();
        } catch (Exception ex) {
            SSLog.e(TAG, ex.toString());
        }
    }

    private String readAllLog() {
        String content = "";
        try {
            File logFile = new File(mLogPath);
            if (logFile.exists() && logFile.isFile()) {
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(logFile), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                StringBuilder contentBuilder = new StringBuilder();
                String temLine = "";
                while ((temLine = bufferedReader.readLine()) != null) {
                    contentBuilder.append(temLine).append("\n");
                }
                content = contentBuilder.toString();
            }
        } catch (Exception ignored) {

        }
        return content;
    }

    public boolean clearLog() {
        try {
            File logFile = new File(mLogPath);
            if (logFile.exists() && logFile.isFile()) {
                if (logFile.delete()) {
                    boolean isSuccess = logFile.createNewFile();
                    writeLog(Util.getTodayTime());
                    return isSuccess;
                }
            }
        } catch (Exception ignored) {

        }
        return false;
    }

    private String getLogPath(Context context) {
        final String LOG_CACHE_DIR = context.getFilesDir().getAbsolutePath() + DIR_LOG + "/";
        final String sdDir = getSDPath();
        final String saveDir = (TextUtils.isEmpty(sdDir)) ? LOG_CACHE_DIR : sdDir;
        if (!doesExisted(saveDir)) {
            assert saveDir != null;
            new File(saveDir).mkdirs();
        }
        return saveDir;
    }

    private boolean doesExisted(String filePath) {
        if (filePath == null || filePath.isEmpty()) {
            return false;
        } else {
            File logFile = new File(filePath);
            return logFile.exists();
        }
    }

    private String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        if (sdDir != null)
            return sdDir.toString();
        else
            return null;

    }

}